package com.lyf.common.serialize;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.lyf.common.api.DataMaskType;
import com.lyf.common.api.JacksonDataMask;

import java.io.IOException;

public class JacksonDataMaskSerializer extends StdSerializer<String> implements ContextualSerializer {
    //脱敏策略枚举
    private DataMaskType dataMask;

    protected JacksonDataMaskSerializer() {
        super(String.class);
    }


    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        JacksonDataMask jacksonDataMask = property.getAnnotation(JacksonDataMask.class);
        if (jacksonDataMask != null && String.class.equals(property.getType().getRawClass())) {
            dataMask = jacksonDataMask.maskType();
            return this;
        }
        return prov.findContentValueSerializer(property.getType(), property);
    }


    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        //执行脱敏
        String resultValue = dataMask.getStrategy().process(value, dataMask.getParams());
        gen.writeString(resultValue);
    }
}